package com.dage.salesflow.kit;

import com.alibaba.excel.util.ListUtils;
import com.dage.salesflow.model.vo.TreeModel;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 处理树形节点
 */
public class TreeKit {
	/**
	 * 向列表中追加所有节点的父节点（递归）
	 */
	public static <M extends TreeModel> List<M> appendParentNodes(List<? extends TreeModel<M>> list) {
		Set pNodes = new HashSet<>();
		for (TreeModel model : list) {
			getParentNodes(model.getParentId(), pNodes, list);
		}
		list.addAll(pNodes);
		return (List<M>) list;
	}

	/**
	 * 递归获取所有子节点
	 */
	public static <M extends TreeModel> List<M> getChildNodes(Integer pid, TreeModel<M> model) {
		List<M> list = model.listChildren(pid);
		List childNodes = ListUtils.newArrayList();
		for (M m : list) {
			childNodes.addAll(getChildNodes(m.getId(), model));
		}
		list.addAll(childNodes);
		return list;
	}

	/**
	 * 递归获取所有父级节点
	 */
	private static <M extends TreeModel> void getParentNodes(int pid, Set nodes, List<? extends TreeModel<M>> list) {
		if (pid <= 0) {
			return;
		}
		boolean exist = false;
		//判断原有集合中是否已经存在
		for (TreeModel node : list) {
			if (node.getId() == pid) {
				exist = true;
				break;
			}
		}
		TreeModel<M> model = list.get(0);
		//不存在时添加父级节点信息
		if (!exist) {
			M node = model.newById(pid);
			if (!nodes.contains(node)) {
				TreeModel n = node.findById(pid);
				nodes.add(n);
				//递归父级菜单
				getParentNodes(n.getParentId(), nodes, list);
			}
		}
	}
}
